/**
 * 设备检测工具
 * 用于检测当前设备类型并返回相应的配置
 */

// 设备类型枚举
export const DeviceType = {
  MOBILE: 'mobile',
  TABLET: 'tablet',
  DESKTOP: 'desktop'
}

// 检测设备类型
export function detectDevice() {
  const userAgent = navigator.userAgent.toLowerCase()
  const isMobile = /mobile|android|iphone|ipad|phone/i.test(userAgent)
  const isTablet = /tablet|ipad/i.test(userAgent)
  const screenWidth = window.innerWidth
  const screenHeight = window.innerHeight
  
  // 桌面端：非移动设备且屏幕宽度大于1024px
  if (!isMobile && !isTablet && screenWidth > 1024) {
    return DeviceType.DESKTOP
  }
  
  // 平板端：屏幕宽度在768px-1024px之间
  if (screenWidth >= 768 && screenWidth <= 1024) {
    return DeviceType.TABLET
  }
  
  // 移动端：其他情况
  return DeviceType.MOBILE
}

// 获取设备配置
export function getDeviceConfig() {
  const deviceType = detectDevice()
  
  const configs = {
    [DeviceType.DESKTOP]: {
      sidebarWidth: 280,
      tableHeight: window.innerHeight - 300,
      maxContentWidth: 'none',
      formColumns: 4,
      mediaColumns: 2,
      feesColumns: 2,
      showStats: true,
      showBreadcrumb: true,
      compactMode: false
    },
    [DeviceType.TABLET]: {
      sidebarWidth: 250,
      tableHeight: 600,
      maxContentWidth: '1200px',
      formColumns: 2,
      mediaColumns: 1,
      feesColumns: 2,
      showStats: false,
      showBreadcrumb: false,
      compactMode: false
    },
    [DeviceType.MOBILE]: {
      sidebarWidth: 0,
      tableHeight: 500,
      maxContentWidth: '1000px',
      formColumns: 1,
      mediaColumns: 1,
      feesColumns: 1,
      showStats: false,
      showBreadcrumb: false,
      compactMode: true
    }
  }
  
  return configs[deviceType]
}

// 响应式断点
export const Breakpoints = {
  MOBILE: 480,
  TABLET: 768,
  DESKTOP: 1024,
  LARGE_DESKTOP: 1200
}

// 检查是否在指定断点范围内
export function isInBreakpoint(min, max) {
  const width = window.innerWidth
  return width >= min && width <= max
}

// 监听设备变化
export function createDeviceWatcher(callback) {
  let currentDevice = detectDevice()
  
  const handleResize = () => {
    const newDevice = detectDevice()
    if (newDevice !== currentDevice) {
      currentDevice = newDevice
      callback(newDevice, getDeviceConfig())
    }
  }
  
  window.addEventListener('resize', handleResize)
  
  // 返回清理函数
  return () => {
    window.removeEventListener('resize', handleResize)
  }
}

// 获取响应式类名
export function getResponsiveClass(deviceType) {
  return {
    'is-mobile': deviceType === DeviceType.MOBILE,
    'is-tablet': deviceType === DeviceType.TABLET,
    'is-desktop': deviceType === DeviceType.DESKTOP
  }
}

// 导出默认配置
export default {
  detectDevice,
  getDeviceConfig,
  createDeviceWatcher,
  getResponsiveClass,
  DeviceType,
  Breakpoints
}
